<template>
  <div>
    <template v-if="modal.status=='manager'">
      <b-modal :ref="capitalize(getLocation(this.location)+'RecordModal')" @ok="onModalHandleCancel" @hide="onModalHandleCancel" :title="modal.title" ok-only>
        <form>
          <b-form-group :style="{display:item.disabled?'none':''}" v-for="item in modal.data" label-class="text-sm-right" horizontal :label-cols="4" breakpoint="md" :description="item.description" :label="item.name" :label-for="item.name">
            <div v-if="item.type=='input'">
              <b-form-input :disabled="modal.edit?!item.edit:true" v-model="modal.alterRecord[item.key]"></b-form-input>
            </div>
            <div v-else-if="item.type=='select'">
              <b-form-select :disabled="modal.edit?!item.edit:true" v-model="modal.alterRecord[item.key]" :options="item.options" class="mb-0" />
            </div>
            <div v-else-if="item.type=='radio'">
              <b-form-radio-group :disabled="modal.edit?!item.edit:true" class="pt-2" v-model="modal.alterRecord[item.key]" :options="item.options" />
            </div>
            <div v-else-if="item.type=='textarea'">
              <b-form-textarea :disabled="modal.edit?!item.edit:true" v-model.trim="modal.alterRecord[item.key]" placeholder="没有信息" :rows="3"></b-form-textarea>
            </div>
          </b-form-group>
          <b-btn :style="{display:!modal.edit?'none':''}" variant="outline-primary" style="float:right;margin-right:8px;padding:6px;font-size:0.7rem" @click="update(modal.alterRecord)">保存</b-btn>
          <b-btn variant="outline-primary" style="float:right;margin-right:8px;padding:6px;font-size:0.7rem" @click="cancalUpdate()">{{modal.edit?'取消修改':'修改'}}</b-btn>
        </form>
      </b-modal>
    </template>
    <template v-else-if="modal.status=='create'">
      <b-modal id="RecordModal" :ref="capitalize(getLocation(this.location)+'RecordModal')" @ok="onModalHandleOk" @hide="onModalHandleCancel" :title="modal.title">
        <form>
          <b-form-group :style="{display:!item.save?'none':''}" v-for="item in modal.data" label-class="text-sm-right" horizontal :label-cols="4" breakpoint="md" :description="item.description" :label="item.name" :label-for="'valid'+item.name" :invalid-feedback="!vaild(modal.entry.save[item.key])?'' : '不能为空'" :valid-feedback="!vaild(modal.entry.save[item.key])?'' : ''" :state="!vaild(modal.entry.save[item.key])?true : false">
            <div v-if="item.type=='input'">
              <b-form-input :state="!vaild(modal.entry.save[item.key])?true : false" :id="'valid'+item.name" v-model="modal.entry.save[item.key]"></b-form-input>
            </div>
            <div v-else-if="item.type=='select'">
              <b-form-select :state="!vaild(modal.entry.save[item.key])?true : false" v-model="modal.entry.save[item.key]" :options="item.options" class="mb-0" />
            </div>
            <div v-else-if="item.type=='radio'">
              <b-form-radio-group :state="!vaild(modal.entry.save[item.key])?true : false" class="pt-2" v-model="modal.entry.save[item.key]" :options="item.options" />
            </div>
            <div v-else-if="item.type=='textarea'">
              <b-form-textarea :state="!vaild(modal.entry.save[item.key])?true : false" v-model.trim="modal.entry.save[item.key]" placeholder="没有信息"></b-form-textarea>
            </div>
          </b-form-group>
        </form>
      </b-modal>
    </template>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import basic from "@/mixins/basic";
import {
  baseURL,
  get,
  save,
  associate,
  getAndAssociate,
  remove,
  update,
  axios
} from "@/service/api";
export default {
  mixins: [basic],
  props: {
    location: {
      type: String,
      default: () => "defects"
    }
  },
  data() {
    return {
      modal: {
        associate: false,
        associateRecord: {},
        currentRecord: {},
        alterRecord: {},
        content: "",
        datas: [
          {
            label: "",
            description: "",
            type: "",
            key: "",
            name: "",
            value: ""
          }
        ],
        entry: {
          save: {}
        },
        edit: false,
        hasData: false,
        property: [],
        status: "create",
        title: ""
      }
    };
  },
  mounted() {
    for (let i = 0; i < this.entry.items.length; i++) {
      if (this.entry.items[i].location == this.getLocation(this.location)) {
        // 深拷贝的一种方法
        this.modal.data = JSON.parse(
          JSON.stringify(this.entry.items[i].modal.property)
        );
        break;
      }
    }
  },
  methods: {
    addAssociate: async function(href, record) {
      let self = this;
      associate(record, href)
        .then(response => {
          if (response.status == "204") {
            alert("关联添加成功");
            self.refresh();
          }
        })
        .catch(error => {
          console.log("添加关联失败");
        });
      this.$emit("update");
    },
    save: async function(playload) {
      console.log(this.modal.hasData);
      if (this.modal.hasData) {
        let self = this;
        await save(this.getLocation(this.location), playload)
          .then(response => {
            if (response.status == "201") {
              alert("资源添加成功");
              if (self.modal.associate) {
                // console.log("关联");
                // console.log(self.modal.associateRecord);
                let amend = response.data;
                // 添加关联
                self.addAssociate(
                  self.modal.associateRecord._links.self.href,
                  amend._links.defect.href
                );
                self.modal.associate = false;
                self.modal.associateRecord = {};
              }
              this.$emit("update");
            }
            console.log(response);
          })
          .catch(error => {
            // console.log("资源添加失败");
            console.log(error);
          });
      }
    },
    update(playload) {
      console.log(this.modal.hasData);
      if (this.modal.hasData) {
        let self = this;
        update(playload._links.self.href, playload)
          .then(response => {
            if (response.status == "200") {
              alert("资源修改成功");
              this.$emit("update");
              this.modal.edit = false;
            }
            console.log(response);
          })
          .catch(error => {
            // console.log("资源修改失败");
            console.log(error);
          });
      }
    },
    cancalUpdate() {
      this.modal.alterRecord = JSON.parse(
        JSON.stringify(this.modal.currentRecord)
      );
      this.modal.edit = !this.modal.edit;
    },
    showModal(title, content, o) {
      this.modal.title = title;
      this.modal.content = content;
      o.show();
    },
    onModalHandleCancel() {
      this.resetModal();
      this.$emit("alter");
    },
    onModalHandleOk(evt) {
      this.onModalHandleSubmit();
    },
    onModalHandleSubmit() {
      this.modal.hasData = true;
      this.save(this.modal.entry.save);
    },
    //关于modal应该关闭时应该重置他的状态
    resetModal() {
      this.modal.title = "";
      this.modal.content = {};
      this.modal.edit = false;
      this.modal.hasData = false;
      this.modal.alterRecord = {};
      this.modal.currentRecord = {};
      this.modal.entry.save = {};
    },
    setModelInfo(item, hasData, status) {
      this.modal.currentRecord = item;
      this.modal.hasData = hasData;
      this.modal.status = status;
    },
    create() {
      // 创建新建实体类
      this.setModelInfo({}, false, "create");
      this.modal.edit = true;
      this.showModal(
        "新建",
        "内容",
        this.$refs[
          this.capitalize(this.getLocation(this.location) + "RecordModal")
        ]
      );
    },
    createAndAssociate(row) {
      this.modal.associate = true;
      this.modal.associateRecord = row;
      // 创建新建实体类
      this.setModelInfo({}, false, "create");
      this.modal.edit = true;
      this.showModal(
        "新建",
        "内容",
        this.$refs[
          this.capitalize(this.getLocation(this.location) + "RecordModal")
        ]
      );
    },
    info(record) {
      this.setModelInfo(record.item, true, "manager");
      this.modal.alterRecord = JSON.parse(JSON.stringify(record.item));
      //this.matchData(record.item);
      this.showModal(
        "信息",
        "内容",
        this.$refs[
          this.capitalize(this.getLocation(this.location) + "RecordModal")
        ]
      );
    }
  },
  computed: {
    ...mapGetters({
      entry: "entry"
    })
  }
};
</script>
<style lang="scss">
.custom-select {
  float: right;
}
</style>
